<?php
/**
 * Created by PhpStorm.
 * User: 我想有个家
 * Date: 2019/9/2
 * Time: 16:08
 */

namespace App\Controller\admin;


use App\Model\Option;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;

/**
 * Class ConfigController
 * @package App\Controller\admin
 * @Controller(prefix="a/config")
 * @Middleware(\App\Middleware\AdminMiddleware::class)
 */
class ConfigController extends AdminBase {
    /**
     * 列表
     * type 1 普通文本 2时间段
     * @return array
     * @RequestMapping(path="lists",methods="get")
     */
    public function getLists() {
        $size = pageSizeVerify($this->get('size'));
        $result = Option::query()
            ->select('id', 'option_name', 'option', 'type', 'limit', 'option_value')
            ->paginate($size);
        return success(paginate($result));
    }

    /**
     * 修改配置值
     * @return array
     * @RequestMapping(path="Value",methods="put")
     */
    public function putValue() {
        $id = $this->body('id');
        $value = $this->body('value');
        if (empty($value)) {
            return error('参数值不能为空');
        }
        //查询配置
        $info = Option::query()->where('id', $id)->select('type', 'limit')->first();
        if (empty($info)) {
            return error('配置不存在');
        }
        switch ($info['type']) {
            case 1:
                $value = (int) $value;
                $info['limit'] = explode(',', $info['limit']);
                if ($value < $info['limit'][0] || $value > $info['limit'][1]) {
                    return error("配置值必须在{$info['limit'][0]}到{$info['limit'][1]}之间数字");
                }
                break;
            case 2:
                $time = explode('-', $value);
                if (count($time) != 2) {
                    return error('配置值格式错误');
                }
                if (!timeCheck($time[0])) {
                    return error('开始时间格式错误');
                }
                if (!timeCheck($time[1])) {
                    return error('结束时间格式错误');
                }
                break;
            default:
                $value = mb_substr($value, 0, 250);
        }
        $res = Option::query()->where('id', $id)->update(['option_value' => $value]);
        if ($res) {
            // 更新缓存
            $service = new Option();
            $service->cache();
        }
        return success();
    }
}
